﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Inscriptionem.Authorization;
using Inscriptionem.Controllers.Base;
using Inscriptionem.Extensions;
using Inscriptionem.Models.Enums;
using Inscriptionem.Models.Requests;
using Inscriptionem.Models.Views;
using Inscriptionem.Services;

namespace Inscriptionem.Controllers
{
    public class MemberController : BaseController
    {
        protected override void Execute(RequestContext requestContext)
        {
            // Override URLs like /1
            if (requestContext.RouteData.Values["action"] != null)
            {
                int id = 0;
                if (int.TryParse(requestContext.RouteData.Values["action"].ToString(), out id))
                {
                    // Rewrite route data
                    requestContext.RouteData.Values["action"] = "index";
                    requestContext.RouteData.Values["id"] = id == 0 ? Member.Current.ID : id;
                }

                if (requestContext.RouteData.Values["id"] == null)
                {
                    requestContext.RouteData.Values["id"] = Member.Current.ID;
                }
            }

            base.Execute(requestContext);
        }

        public ActionResult Index(int id)
        {
            var member = new ORM.DB().Members.FirstOrDefault(m => m.ID == id);
            if (member == null)
            {
                return new HttpNotFoundResult();
            }

            return View("Index", member);
        }

        [InscriptionemAuthorize(MemberRole.Admin, MemberRole.Member, MemberRole.Moderator, MemberRole.Writer)]
        public ActionResult Edit()
        {
            var member = new ORM.DB().Members.FirstOrDefault(m => m.ID == Member.Current.ID);

            var result = new MemberViewModel()
                             {
                                 ID = member.ID,
                                 FirstName = member.FirstName,
                                 NickName = member.NickName,
                                 LastName = member.LastName,
                                 BirthDate = member.BirthDate,
                                 Mail = member.Mail,
                                 SiteLink = member.MemberSettings.SiteLink,
                                 Description = member.MemberSettings.Description
                             };

            return View("Edit", result);
        }

        [HttpPost]
        [InscriptionemAuthorize(MemberRole.Admin, MemberRole.Member, MemberRole.Moderator, MemberRole.Writer)]
        public ActionResult Edit(MemberRequestModel model)
        {
            var result = new MemberViewModel();
            model.CopyTo(result);

            result.Error = ValidateMemberModel(result);
            if (!string.IsNullOrWhiteSpace(model.Password) && !string.IsNullOrWhiteSpace(model.PasswordConfirmation))
            {
                if (model.Password != model.PasswordConfirmation)
                {
                    result.Error = MemberError.PasswordNotMatch;
                }
                else if (model.Password.Length < 6)
                {
                    result.Error = MemberError.PasswordLength;
                }
            }

            var db = new ORM.DB();

            var member = db.Members.First(m => m.ID == Member.Current.ID);
            result.Mail = member.Mail;


            if (result.Error == MemberError.None)
            {
                try
                {
                    member.FirstName = result.FirstName.Trim();
                    member.NickName = result.NickName.Trim();
                    member.LastName = result.LastName.Trim();

                    member.BirthDate = result.BirthDate;

                    if (!string.IsNullOrWhiteSpace(model.Password))
                    {
                        member.Password = EncryptionService.EncryptString(result.Mail, model.Password);
                    }

                    member.MemberSettings.Description = result.Description.Trim();
                    member.MemberSettings.SiteLink = result.SiteLink;

                    member.ModifiedDate = DateTime.Now;
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    result.Error = MemberError.Other;
                }
            }

            return View("Edit", result);
        }

        private MemberError ValidateMemberModel(MemberViewModel Model)
        {
            if (string.IsNullOrWhiteSpace(Model.FirstName))
            {
                return MemberError.FirstNameEmpty;
            }

            if (string.IsNullOrWhiteSpace(Model.LastName))
            {
                return MemberError.LastNameEmpty;
            }

            if (!Model.SiteLink.ToLower().StartsWith("http"))
            {
                return MemberError.SiteLink;
            }

            return MemberError.None;
        }
    }
}